<template>
  <div class="roles_wrap">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{}">权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-button type="primary" @click="addRoleDialogVisible = true">
        添加角色
      </el-button>
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bd_top', i1 == 0 ? '' : 'bd_bottom', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  @close="removeRightsById(scope.row, item1.id)"
                  closable
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 == 0 ? '' : 'bd_top', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      @close="removeRightsById(scope.row, item2.id)"
                      closable
                      >{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <!-- 
                      closable  提供关闭的小图标 
                      @close  绑定关闭事件会触发对应的函数
                  -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      :class="[i3 == 0 ? '' : 'bd_top']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      @close="removeRightsById(scope.row, item3.id)"
                      closable
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="" label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRoleForm(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
            >
              删除
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setRightsDialog(scope.row)"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
    >
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRules"
        ref="addRoleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="50%"
    >
      <el-form
        :model="editRoleObj"
        :rules="addRoleFormRules"
        ref="editRoleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleObj.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleObj.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole(editRoleObj.roleId)">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
    >
      <el-form ref="setRightsFormRef" label-width="100px" class="demo-ruleForm">
        <!-- 
            树形控件
            data  绑定数据源
            show-checkbox  展示复选框
            node-key  每个树节点用来作为唯一标识的属性，整棵树应该是唯一的
            default-expand-all  是否默认展开所有节点，默认false
            default-checked-keys  默认勾选的节点的 key 的数组
         -->
        <el-tree
          :data="setRightsTree"
          :props="rightsProps"
          ref="treeRef"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="defaultKeys"
        ></el-tree>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="alloRights"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 保存角色列表数据
      rolesList: [],
      addRoleDialogVisible: false, // 添加角色对话框的显示与隐藏
      // 添加角色数据对象
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      // 添加角色定义规则，编辑角色的规则也一样
      addRoleFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur',
          },
        ],
      },
      // 编辑角色对话框的显示与隐藏
      editRoleDialogVisible: false,
      // 编辑角色对象
      editRoleObj: {},
      setRightsDialogVisible: false, // 分配权限对话框
      setRightsTree: [], // 所有权限
      // 树形控件的属性绑定对象
      rightsProps: {
        // 指定节点标签为节点对象的某个属性值，展示的文本
        label: 'authName',
        // 指定子树为节点对象的某个属性值
        children: 'children',
      },
      // 默认选中节点的id值数组
      defaultKeys: [],
      // 当前角色的id
      roleId: '',
    }
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('获取角色列表失败')
      this.rolesList = res.data
    },
    // 根据id删除权限（角色id和权限id）
    async removeRightsById(role, rightId) {
      // console.log(roleId, rightId)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(confirmResult)
      if (confirmResult === 'cancel') return
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('删除权限失败')
      this.$msg.success('删除权限成功')
      // 会直接合上展开区
      // this.getRolesList()
      role.children = res.data
    },
    // 添加角色
    async addRole() {
      // 校验失败
      this.$refs.addRoleFormRef.validate((valid) => {
        if (!valid) return
      })
      const { data: res } = await this.$http.post('roles', this.addRoleForm)
      // console.log(res)
      if (res.meta.status !== 201) return this.$msg.error('添加角色失败')
      this.$msg.success('添加角色成功')
      this.addRoleDialogVisible = false
      this.getRolesList()
    },
    // 控制编辑角色对话框
    async editRoleForm(role) {
      this.editRoleDialogVisible = true
      const { data: res } = await this.$http.get(`roles/${role.id}`)
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('查询角色信息失败')
      this.editRoleObj = res.data
    },
    // 编辑角色
    editRole(id) {
      this.$refs.editRoleFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(`roles/${id}`, {
          roleName: this.editRoleObj.roleName,
          roleDesc: this.editRoleObj.roleDesc,
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$msg.error('编辑角色失败')
        this.$msg.success('编辑角色成功')
        this.editRoleDialogVisible = false
        this.getRolesList()
      })
    },
    // 根据id删除角色
    async removeRoleById(id) {
      //   console.log(id)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(confirmResult)
      if (confirmResult === 'cancel') return
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) return this.$msg.error('删除角色失败')
      this.$msg.success('删除角色成功')
      this.getRolesList()
    },
    // 分配权限对话框
    async setRightsDialog(role) {
      this.roleId = role.id
      this.setRightsDialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('查询权限失败')
      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defaultKeys)
      this.setRightsTree = res.data
    },
    // 递归获取角色下所有三级权限的id，并保存到defaultKeys数组中
    getLeafKeys(node, arr) {
      // 是三级节点，把id添加到数组中
      if (!node.children) {
        return arr.push(node.id)
      }
      // 不是三级节点，递归
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightsDialogClosed() {
      // 清空原先保存的选中三级节点
      this.defaultKeys = []
    },
    // 分配权限
    async alloRights() {
      /*
        需要拿到选中权限的id，以及父权限的id，tree组件中提供了两个函数
        getCheckedKeys  拿到选中节点的id
        getHalfCheckedNodes  拿到半选中节点的id，即父节点的id
      */
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedNodes(),
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr,
        }
      )
      console.log(idStr)
      if (res.meta.status !== 200) return this.$msg.error('更新角色权限失败')
      this.$msg.success('更新角色权限成功')
      this.getRolesList()
      this.setRightsDialogVisible = false
    },
  },
  beforeMount() {
    this.getRolesList()
  },
}
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-row {
  margin-left: 30px;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 14px;
}
.bd_top {
  border-top: 1px solid #eee;
}
.bd_bottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>